package flc.ast.fragment;

import android.Manifest;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.filter.Filters;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.adapter.CameraFilterAdapter;
import flc.ast.adapter.StickerAdapter;
import flc.ast.bean.MyCameraFilterBean;
import flc.ast.bean.MyStickerBean;
import flc.ast.databinding.FragmentCameraBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CameraFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CameraFragment extends BaseNoModelFragment<FragmentCameraBinding> {

    //贴纸
    private StickerAdapter stickerAdapter;
    private int oldStickerPos = 0;
    //滤镜
    private CameraFilterAdapter filterAdapter;
    private int oldFilterPos = 0;
    private int funcSelPos = 0;
    private Bitmap mRetBitmap;

    @Override
    protected int onCreate() {
        return R.layout.fragment_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraSticker.setOnClickListener(this);
        mDataBinding.ivCameraFilter.setOnClickListener(this);
        mDataBinding.ivFuncBack.setOnClickListener(this);
        mDataBinding.tvCameraSticker.setOnClickListener(this);
        mDataBinding.tvCameraFilter.setOnClickListener(this);
        mDataBinding.ivSaveBack.setOnClickListener(this);
        mDataBinding.ivSaveDownload.setOnClickListener(this);
        mDataBinding.llBottomMain.setOnClickListener(null);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraStart://开始拍摄
                if (mDataBinding.cameraView.isTakingPicture()) return;
                mDataBinding.cameraView.takePictureSnapshot();
                mDataBinding.ivStickerView.setShowHelpToolFlag(false);
                break;
            case R.id.ivCameraSticker://滤镜
                mDataBinding.llBottomMain.setVisibility(View.GONE);
                mDataBinding.llBottomFunc.setVisibility(View.VISIBLE);
                funcSelPos = 0;
                clearSelection();
                mDataBinding.tvCameraSticker.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivStickerSel.setVisibility(View.VISIBLE);
                mDataBinding.rvStickerList.setVisibility(View.VISIBLE);
                break;
            case R.id.ivCameraFilter://滤镜
                mDataBinding.llBottomMain.setVisibility(View.GONE);
                mDataBinding.llBottomFunc.setVisibility(View.VISIBLE);
                funcSelPos = 1;
                clearSelection();
                mDataBinding.tvCameraFilter.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivFilterSel.setVisibility(View.VISIBLE);
                mDataBinding.rvFilterList.setVisibility(View.VISIBLE);
                break;
            case R.id.tvCameraSticker://贴纸选中
                funcSelPos = 0;
                clearSelection();
                mDataBinding.tvCameraSticker.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivStickerSel.setVisibility(View.VISIBLE);
                mDataBinding.rvStickerList.setVisibility(View.VISIBLE);
                break;
            case R.id.tvCameraFilter://滤镜选中
                funcSelPos = 1;
                clearSelection();
                mDataBinding.tvCameraFilter.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivFilterSel.setVisibility(View.VISIBLE);
                mDataBinding.rvFilterList.setVisibility(View.VISIBLE);
                break;
            case R.id.ivFuncBack://贴纸/滤镜返回
                mDataBinding.llBottomMain.setVisibility(View.VISIBLE);
                mDataBinding.llBottomFunc.setVisibility(View.GONE);
                break;
            case R.id.ivSaveBack://保存返回
                mDataBinding.rlCamera.setVisibility(View.VISIBLE);
                mDataBinding.rlSave.setVisibility(View.GONE);
                break;
            case R.id.ivSaveDownload://保存
                saveImg();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == stickerAdapter) {
            Resources res = getResources();
            Bitmap bmp = BitmapFactory.decodeResource(res, stickerAdapter.getItem(position).getImg());
            mDataBinding.ivStickerView.addBitImage(bmp);
        } else if (adapter == filterAdapter) {
            //设置滤镜
            filterAdapter.getItem(oldFilterPos).setSelect(false);
            oldFilterPos = position;
            filterAdapter.getItem(position).setSelect(true);
            filterAdapter.notifyDataSetChanged();
            mDataBinding.cameraView.setFilter(filterAdapter.getItem(position).getFilter());
        }
    }

    @Override
    protected void initData() {
        getPermission();
        //贴纸数据
        List<MyStickerBean> mStickerList = new ArrayList<>();//贴纸集合
        mStickerList.add(new MyStickerBean(R.drawable.iv_tz1, getString(R.string.sticker_name1)));
        mStickerList.add(new MyStickerBean(R.drawable.iv_tz2, getString(R.string.sticker_name2)));
        mStickerList.add(new MyStickerBean(R.drawable.iv_tz3, getString(R.string.sticker_name3)));
        mStickerList.add(new MyStickerBean(R.drawable.iv_tz4, getString(R.string.sticker_name4)));
        mStickerList.add(new MyStickerBean(R.drawable.iv_tz5, getString(R.string.sticker_name5)));
        mDataBinding.rvStickerList.setLayoutManager(new GridLayoutManager(mContext, 5));
        stickerAdapter = new StickerAdapter();
        mDataBinding.rvStickerList.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);
        stickerAdapter.setList(mStickerList);
        //滤镜数据
        List<MyCameraFilterBean> mFilterList = new ArrayList<>();//滤镜集合
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text1), "#00000000", Filters.values()[0].newInstance(), true));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text2), "#323333", Filters.values()[1].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text3), "#C376F3", Filters.values()[2].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text4), "#6F7171", Filters.values()[3].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text5), "#505151", Filters.values()[4].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text6), "#999999", Filters.values()[5].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text7), "#513232", Filters.values()[6].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text8), "#787A7A", Filters.values()[7].newInstance(), false));
        mDataBinding.rvFilterList.setLayoutManager(new GridLayoutManager(mContext, 5));
        filterAdapter = new CameraFilterAdapter();
        mDataBinding.rvFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
        filterAdapter.setList(mFilterList);
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                setStickerMark(result);
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //设置图片贴纸
    private void setStickerMark(PictureResult result) {
        int width = result.getSize().getWidth();
        int height = result.getSize().getHeight();
        int screenWidth = DensityUtil.getWith(getContext());
        int screenHeight = DensityUtil.getHeight(getContext());
        if (width * height > screenWidth * screenHeight) {
            width = screenWidth;
            height = screenHeight;
        }
        result.toBitmap(width, height, new BitmapCallback() {
            @Override
            public void onBitmapReady(@Nullable Bitmap bitmap) {

                //有水印时的处理
                Bitmap retBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(retBitmap);
                //核心点2：计算水印控件在所拍照片上的正确的位置
                float left = retBitmap.getWidth() * (mDataBinding.ivStickerView.getLeft() * 1f / mDataBinding.rlCamera.getWidth());
                float top = retBitmap.getHeight() * (mDataBinding.ivStickerView.getTop() * 1f / mDataBinding.rlCamera.getHeight());
                canvas.drawBitmap(ImageUtils.view2Bitmap(mDataBinding.ivStickerView), left, top, null);
                mRetBitmap = retBitmap;
                mDataBinding.ivSaveImg.setImageBitmap(mRetBitmap);
                mDataBinding.rlCamera.setVisibility(View.GONE);
                mDataBinding.rlSave.setVisibility(View.VISIBLE);
            }
        });
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到相册
                        ImageUtils.save2Album(mRetBitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        mDataBinding.rlCamera.setVisibility(View.VISIBLE);
                        mDataBinding.rlSave.setVisibility(View.GONE);
                    }
                });
            }
        }, 500);
    }

    private void clearSelection() {
        mDataBinding.tvCameraSticker.setTextColor(Color.parseColor("#A1A1A1"));
        mDataBinding.ivStickerSel.setVisibility(View.GONE);
        mDataBinding.rvStickerList.setVisibility(View.GONE);
        mDataBinding.tvCameraFilter.setTextColor(Color.parseColor("#A1A1A1"));
        mDataBinding.ivFilterSel.setVisibility(View.GONE);
        mDataBinding.rvFilterList.setVisibility(View.GONE);
    }

}